<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Authorize extends MY_Controller {
	public function __construct() {
		parent::__construct();

        $this->lang->load('error', 'vietnamese');
        $this->lang->load('form_validation', 'vietnamese');
        $this->load->library('form_validation');
	}

    public function renderView($view, $data){
    	$pageHtml = $this->load->view($view.'.html.php', $data, true);
    	$this->load->view('backend/layout/layout-user.html.php', array('pageHtml'=>$pageHtml));
    }

	public function login() {
		$aReturn = array();
        $aLogin  = $this->input->post('lg', true);
        $this->form_validation->set_rules('lg[username]', 'lang:username', 'trim|required|max_length[150]|xss_clean');
		$this->form_validation->set_rules('lg[password]', 'lang:password', 'trim|required|max_length[100]|min_length[8]');
		$this->form_validation->set_error_delimiters('<li>', '</li>');
		if ($this->form_validation->run() == false) {
			$aReturn = array(
				'code'    => 0,
				'message' => $this->lang->line('login_fail'),
				'details' => validation_errors());
		} else {
			$this->load->model('repo/user_model', 'user_model');
			$objUser = $this->user_model->login($aLogin);
			if ($objUser == null) {
				$aReturn = array(
					'code'    => 0,
					'message' => $this->lang->line('login_fail'),
					'details' => '<li>' . $this->lang->line('login_condition_fail') . '</li>');
			} else {
                //set session
				$newdata = array(
					'user_id'      => $objUser->getId(),
					'name'         => $objUser->getFullName(),
                    'image_folder' => $objUser->getImageFolder(),
                    'image'        => $objUser->getImage(),
					'role'         => $objUser->getRole()
                );
				$this->session->set_userdata($newdata);

                //login success
                $ref = $this->input->get('ref', true);
                if($ref!=false){
                	$link = $ref;
                } elseif(strpos($_SERVER['HTTP_REFERER'], 'dang-nhap')!==false){
					$link = page_url();
				} elseif(strpos($_SERVER['HTTP_REFERER'], 'quen-mat-khau')!==false){
					$link = page_url();
				} else {
					$link = $_SERVER['HTTP_REFERER'];
				}
				if(isset($aLogin['backlink'])){
					$link = $aLogin['backlink'];
				}
				$aReturn = array(
					'code'    => 1,
					'message' => $this->lang->line('login_success'),
					'href'    => $link
				);
			}
		}
		$this->renderJSON($aReturn);
	}

	public function logout() {
		$backlink = $this->input->get('ref');
		$this->load->model('repo/user_model', 'user_model');
		$result = $this->user_model->logout($this->user_id);
		if($result){
			//$this->session->sess_destroy();
			$this->session->unset_userdata('user_id');
			$this->session->unset_userdata('name');
			$this->session->unset_userdata('image_folder');
			$this->session->unset_userdata('image');
			$this->session->unset_userdata('role');
			if($backlink!=false){
				redirect($backlink);
			} else {
				redirect(page_url());
			}
		} else {
			show_404();
		}
	}

	public function signup() {
		$aSignup = $this->input->post('signup', true);
		$this->form_validation->set_rules('signup[full_name]', 'lang:fullname',   'trim|required|max_length[150]|xss_clean');
		$this->form_validation->set_rules('signup[username]',  'lang:username',   'trim|required|max_length[50]|callback_username_check|xss_clean');
		$this->form_validation->set_rules('signup[password]',  'lang:password',   'trim|required|max_length[100]|min_length[8]');
		$this->form_validation->set_rules('repassword',        'lang:repassword', 'trim|required|max_length[100]|callback_repassword_check[repassword]');
		$this->form_validation->set_rules('signup[email]',     'lang:email',      'trim|required|valid_email|max_length[150]');
		$this->form_validation->set_error_delimiters('<li>', '</li>');

		$aReturn = array();
		if ($this->form_validation->run() == false) {
			$aReturn = array(
				'code'    => 0,
				'message' => $this->lang->line('signup_fail'),
				'details' => validation_errors());
		} else {
			$curDateTime = new DateTime('now');
			$aSignup['active_code'] = md5($aSignup['username'] . ($curDateTime->format('Y-m-d H:i:s')));
			$aSignup['password'] = $this->encrypt->encode($aSignup['password']);
			$aSignup['created_at'] = $curDateTime->format(DATE_TIME_FORMAT);
            $this->load->model('repo/user_model', 'user_model');
			$result = $this->user_model->signup($aSignup);
			if ($result) {
                $aReturn = array(
					'code'    => 1,
					'message' => $this->lang->line('signup_success'),
					'details' => '<li>' . $this->lang->line('signup_success_instruct') . '</li>');
			} else {
				$aReturn = array(
					'code'    => 0,
					'message' => $this->lang->line('signup_fail'),
					'details' => '<li>' . $this->lang->line('duplicate_username_email') . '</li>');
			}
		}
		$this->renderJSON($aReturn);
	}

	public function active() {
        $this->load->model('repo/user_model', 'user_model');
		$code = $this->input->get('code', true);
		$user = $this->user_model->getUserByActiveLink($code);
		if (count($user) > 0) {
			$this->load->model('repo/page_model', 'page_model');
			$this->load->model('repo/category_model', 'cate_model');
			$aPages = $this->page_model->getPages();
			$aReturn = array(
				'user' => $user,
				'aPages'    => $aPages,
				'action'    => 'active',
				'pageTitle' => 'Kích hoạt tài khoản'
				);
			$this->renderView('backend/user/active', $aReturn);
		} else {
			show_404();
		}
	}

	public function doActive()
	{
		$active = $this->input->post('active', true);
		$this->form_validation->set_rules('active[password]',  'lang:password',       'trim|required|max_length[100]|min_length[8]');
		$this->form_validation->set_rules('active[phone]',     'lang:active_phone',   'trim|required|numeric|min_length[9]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('active[address]',   'lang:active_address', 'trim|required|max_length[160]|xss_clean');
		$this->form_validation->set_rules('active[full_name]', 'lang:fullname',       'trim|required|max_length[150]|xss_clean');
		$this->form_validation->set_error_delimiters('<li>', '</li>');

		$aReturn = array();
		if ($this->form_validation->run() == false) {
			$aReturn = array(
				'code'    => 0,
				'message' => $this->lang->line('active_fail'),
				'details' => validation_errors());
		} else {
			$date = new DateTime();
			$this->load->model('repo/user_model', 'user_model');
            $user = $this->user_model->getUserTempById($this->encrypt->decode($active['id']));
			if ($user != null) {
				if ($this->encrypt->decode($user->getPassword()) == $active['password'] && $user->getUsername() == $active['username']) {
					$user->setActiveFlg(1);
					$user->setRole(ROLE_ADVERTISER);
					$user->setGender($active['gender']);
					$user->setBirthday($active['birthday']);
					$user->setAddress($active['address']);
					$user->setPhone($active['phone']);
					$user->setImageFolder('');
					$user->setUpdatedAt($date->format(DATE_TIME_FORMAT));
					$result = $this->user_model->active($user, $user->getId());

					if ($result) {
						$aReturn = array(
							'code'    => 1,
							'message' => $this->lang->line('active_success') . "</li>",
							'href'    => page_url()
							);
					} else {
						$aReturn = array(
							'code'    => 0,
							'message' => $this->lang->line('active_fail'),
							'details' => "<li>" . $this->lang->line('active_transaction_fail') . "</li>");
					}
				} else {
					$aReturn = array(
						'code'    => 0,
						'message' => $this->lang->line('active_fail'),
						'details' => "<li>" . $this->lang->line('active_user_not_found') . "</li>");
				}
			} else {
				$aReturn = array(
					'code'    => 0,
					'message' => $this->lang->line('active_fail'),
					'details' => "<li>" . $this->lang->line('active_link_expired') . "</li>");
			}
		}
		$this->renderJSON($aReturn);
	}

	public function doForgetPassword(){
		$aReturn = array();
        $email = $this->input->post('email', true);
        $this->form_validation->set_rules('email', 'lang:email', 'trim|required|valid_email|max_length[150]');
		$this->form_validation->set_error_delimiters('<li>', '</li>');
        if($this->form_validation->run() == false){
            $aReturn = array(
				'code' => 0,
				'message' => $this->lang->line('reset_fail'),
				'details' => validation_errors());
        } else {
            $code = md5(rand() . get_current_date());
            $this->load->model('repo/user_model', 'user_model');
    		$result = $this->user_model->createForgetPasswordRequest($email, $code);
    		if(!$result){
    			$aReturn = array(
    				'code'    => 0,
    				'message' => $this->lang->line('user_not_found')
                );
    		} else {
  		        //response ok
                $aReturn = array(
    				'code'    => 1,
    				'message' => $this->lang->line('do_forget_success')
                );
    		}
        }
        $this->renderJSON($aReturn);
	}

	public function resetPassword(){
		$code = $this->input->get('code', true);
        $this->load->model('repo/user_model', 'user_model');
		$user = $this->user_model->getForgetPasswordUserByActiveLink($code);
		if(count($user)>0){
			$this->load->model('repo/page_model', 'page_model');
			$aPages = $this->page_model->getPages();
			$aReturn = array(
				'reuser'    => $user,
				'aPages'    => $aPages,
				'action'    => 'active',
				'pageTitle' => 'Tạo mật khẩu mới'
				);
			$this->renderView('backend/user/reset-password', $aReturn);
			return;
		}
		show_404();
	}

	public function doResetPassword(){
		$user = $this->input->post('re',true);
		$usertemp = $this->input->post('re');
		$this->form_validation->set_rules('re[password]', 'lang:password',   'trim|required|max_length[100]|min_length[8]|xss_clean');
		$this->form_validation->set_rules('repassword',   'lang:repassword', 'trim|required|max_length[100]|min_length[8]|callback_repassword_check[repassword]|xss_clean');
		$this->form_validation->set_error_delimiters('<li>', '</li>');
		$aReturn = array();
		if ($this->form_validation->run() == false) {
			$aReturn = array(
				'code'    => 0,
				'message' => $this->lang->line('reset_fail'),
				'details' => validation_errors());
		} else {
			$user_temp_id = $this->encrypt->decode($usertemp['v1']);
			$user_id      = $this->encrypt->decode($usertemp['v2']);
			if($user_id==false || $user_temp_id==false){
				$aReturn = array(
					'code'    => 0,
					'message' => $this->lang->line('system_error'),
					'details' => validation_errors()
				);
			} else {
				$this->load->model('repo/user_model', 'user_model');
				$result = $this->user_model->updateForgetPasswordUserByActiveLink($user_temp_id, $user_id, $this->encrypt->encode($user['password']));
				if(!$result){
					$aReturn = array(
						'code'    => 0,
						'message' => $this->lang->line('system_error'),
						'details' => validation_errors()
					);
				} else {
					$aReturn = array(
						'code'    => 1,
						'message' => $this->lang->line('reset_success') . "</li>",
						'href'    => page_url()
					);
				}
			}
		}
		$this->renderJSON($aReturn);
	}
}
?>